import echarts from 'echarts'

class Stack {

  constructor (chart, params = {}) {
    this._chart = chart
    this._params = params
    this._option = null
  }

  render (source) {
    const option = this.getOptions({ source, ...this._params })
    this._chart.setOption(option)
  }

  getOptions ({ source, color = '#708DE8' }) {
    const { xAxisData, series, legendData } = this._translateSource(source)

    return {
      color: color,
      legend: {
        top: '10',
        data: legendData
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      grid: {
        top: 50,
        left: '12%',
        bottom: 40,
        right: '6%'
      },
      xAxis: [
        {
          type: 'category',
          data: xAxisData,
          axisLine: {
            symbol: ['none', 'arrow'],
            symbolSize: [5, 5],
            symbolOffset: [0, 5]
          }
        }
      ],
      yAxis: [
        {
          type: 'value',
          axisLine: {
            symbol: ['none', 'arrow'],
            symbolSize: [5, 5],
            symbolOffset: [0, 5]
          }
        }
      ],
      series
    }
  }

  _translateSource (source) {
    const getValue = (source = [], data = []) => {
      return source.map(item => {
        let obj = data.find(v => v.name === item)
        return obj ? obj.value : 0
      })
    }
    const isMultiple = source.filter(item => Array.isArray(item.value)).length > 0
    const legendData = isMultiple ? source.map(item => item.name) : []
    const xAxisData = source.reduce((results, item) => {
      return isMultiple ?
        Array.from(new Set(results.concat(item.value.map(v => v.name)))) :
        results.concat(item.name)
    }, [])
    const series = isMultiple ?
      source.map(item => ({
        type: "line",
        name: item.name,
        data: getValue(xAxisData, item.value)
      })) :
      [{
        type: "line",
        data: getValue(xAxisData, source)
      }]
    return {
      legendData,
      xAxisData,
      series
    }
  }
}

export default Stack
